#ifndef CARTUI_H
#define CARTUI_H

#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QScrollArea>
#include <QFrame>
#include <QGroupBox>
#include <QTableWidget>
#include <QHeaderView>
#include <QMessageBox>
#include <QTimer>
#include "../data/models.h"
#include "../business/ordermanager.h"
#include "../business/menumanager.h"

// 使用命名空间
using namespace RestaurantSystem;

/**
 * @brief 购物车项模型 - 简化版本
 */
struct CartItem {
    QString menuItemId;
    QString menuItemName;
    double price;
    int quantity;
    double subtotal;
    int availableStock;  // 可用库存
    
    CartItem() = default;
    CartItem(const QString& id, const QString& name, double p, int qty, int stock)
        : menuItemId(id), menuItemName(name), price(p), quantity(qty), availableStock(stock) {
        subtotal = price * quantity;
    }
    
    void calculateSubtotal() {
        subtotal = price * quantity;
    }
    
    bool canIncreaseQuantity() const {
        return quantity < availableStock;
    }
    
    int getMaxAllowedQuantity() const {
        return availableStock;
    }
};

/**
 * @brief 顾客端购物车界面类 - 简化版本
 */
class CustomerCartUI : public QWidget
{
    Q_OBJECT

public:
    explicit CustomerCartUI(QWidget *parent = nullptr);
    ~CustomerCartUI();

    void setManagers(OrderManager *orderManager, MenuManager *menuManager);
    void setCurrentUserId(int userId);
    void addItemToCart(const QString &menuItemId, int quantity);
    void clearCart();
    void clearCartForUserSwitch();
    
    // 重新下单功能扩展
    ReorderResult addItemsFromOrder(const QList<OrderItem>& items);
    ReorderResult replaceCartWithOrder(const QList<OrderItem>& items);

signals:
    void orderSubmitted(const QString &orderId);
    void cartChanged(int itemCount, double totalAmount);
    void backToMenuRequested();
    void batchAddCompleted(const ReorderResult& result);

private slots:
    void handleCheckout();
    void handleBackToMenu();
    void handleClearCart();
    void handleQuantityChanged(int value);
    void handleRemoveItem();

private:
    void initializeUI();
    void updateCartDisplay();
    void calculateTotals();

private:
    OrderManager *m_orderManager;
    MenuManager *m_menuManager;
    int m_currentUserId;

    QVBoxLayout *m_mainLayout;
    QLabel *m_titleLabel;
    QPushButton *m_backButton;
    QTableWidget *m_cartTable;
    QLabel *m_totalLabel;
    QPushButton *m_clearButton;
    QPushButton *m_checkoutButton;

    QList<CartItem> m_cartItems;
    double m_totalAmount;
};

#endif // CARTUI_H
